import * as io from '../services/socketio'

import { data_cols, data_cols2 } from '../../config/data'
import { msg } from '../utils/msg'

import { get_list_all } from '../pages/home/methods'

// 获取系统档案表格表头数据
const keys = Object.keys(data_cols)
const table_cols = () => {
    var cols = []
    keys.forEach(key => {
        var col = {
            key: key,
            dataIndex: key,
            title: data_cols[key][0].split("（")[0],
            width: data_cols[key][1],
            multi: data_cols[key][4],
        }
        if (data_cols[key][3] !== '') col['fixed'] = data_cols[key][3]
        cols.push(col)
    });
    return cols
}

// 生成标签绑定表
const tags_bind = () => {
    let tags = {}
    keys.forEach(key => {
        tags[key] = []
    });
    return tags
}

export default {
    namespace: 'global',

    state: {
        keys: keys,
        table_cols: table_cols(),
        upload_file: '',
        file_cols: [],
        file_data: [],
        file_data_cols: [],
        tag_bind: tags_bind(),
        file_tags: table_cols().filter(i => i).map(col => col.title),
        format_file_data: [],
        workbook: null,
        sheet_names: [],
        sheet: '',

        list_all: []
    },

    reducers: {
        save(state, action) {
            return { ...state, ...action.payload };
        },
    },

    effects: {
        *fetch({ payload }, { call, put }) {
            yield put({ type: 'save', payload: payload });
        },
    },

    subscriptions: {
        // 订阅SOCKET消息事件
        socketio({ dispatch }) {
            io.listen(action => {
                switch (action.type) {
                    // 监听链接成功事件
                    case 'connect':
                        msg(action.state, action.msg)
                        break

                    case 'list':
                        console.log('收到列表文件')
                        dispatch({
                            type: 'save',
                            payload: { list_all: action.data }
                        })
                        break


                    // 处理消息提示事件
                    default:
                        msg(action.state, action.msg)
                        break;
                }
            })
        },
        init({ dispatch, history }) {
            history.listen(({ pathname, query }) => {
                if (pathname === '/home/list') {
                    get_list_all()
                }
            })
        }
    },

};